package com.example.binarytree;

/**
 * @author Jonathan
 * 2021/4/15 20:57
 */
public class BalanceTree {


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public static class Info {
        public boolean isBalanced;
        public int height;

        public Info(boolean isBalanced, int height) {
            this.isBalanced = isBalanced;
            this.height = height;
        }
    }


    public boolean isBalanced(TreeNode root) {
        return process(root).isBalanced;
    }

    public Info process(TreeNode x) {
        if (x == null) {
            return new Info(true, 0);
        }

        Info leftInfo = process(x.left);
        Info rightInfo = process(x.right);
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        // 假设是平衡二叉树
        boolean isBalanced = true;
        // 判断是不是
        if (!leftInfo.isBalanced || !rightInfo.isBalanced ||
                Math.abs(leftInfo.height - rightInfo.height) > 1) {
            isBalanced = false;
        }
        return new Info(isBalanced, height);
    }

    public static void main(String[] args) {
        BalanceTree balanceTree = new BalanceTree();
        boolean balanceTreeBalanced = balanceTree.isBalanced(null);
        System.out.println(balanceTreeBalanced);

    }
}
